<?php
/**
 * 区域扩展模型，未直接用外层模型是为了单独处理些数据
 * AdminAreaHandle.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * -------------------------------
 * 
 * @package xcs
 * @author huangdaohai <huangdaohai.2007@163.com>
 * @version V1.0
 * @access public
 */
class AdminAreaHandle extends BaseAreaModel
{
	/**
	 * 根据区域ID获取一条信息
	 * @param integer $aid
	 * 
	 * @return array
	 */
	public function getOne($aid)
	{
		$result = self::model()->findByPk($aid);

		return $result;
	}
	
	public function getInfos($arr)
	{
		$result = self::model()->findAll("area_id in(".implode(',',$arr).")");
		return $result;
	}
	
	/**
	 * 根据省ID和市ID县ID获取到省市县字符串
	 * @param string $aid 最低级地区id
	 * @param string $rank （1表只取省；1,2表取省市；1,2,3表取省市县（默认值）；
	 * 
	 * @return array
	 */
	public function getAreaStr($aid, $rank='1,2,3')
	{
		$areaarr = $areaids = $rankarr = array();
		$r_str = $fids = "";
		
		$areaOne = $this->getOne($aid);
		$fids = $areaOne['fids'];
		
		$fids = trim($fids, ',');
		$areaids = explode(',', $fids);
		$rank = !empty($rank) ? $rank : '1,2,3';
		$rankarr = explode(',', $rank);

	    if(!empty($fids)){
	        $result = self::model()->findAll("area_id in (".$fids.")");
	        if(!empty($result)){
	            foreach ($result as $k => $v){
	                $areaarr[$v['area_id']] = $v['name'];
	            }
	            foreach ($areaids as $kk => $vv){
    	            if(!empty($vv) && in_array($kk+1,$rankarr)){
    	                $r_str .= $areaarr[$vv];
    	            }
	           }
	        }
	    }

		return $r_str;
	}
	
	/**
	 * 获取菜单列表
	 *
	 * @param array $params
	 * @return array 
	 */
	public function getList($params)
	{
		$page = (isset($params['page']) && !empty($params['page'])) ? $params['page'] : 1;
		$page_size = (isset($params['page_size']) && !empty($params['page_size'])) ? $params['page_size'] : Yii::app()->params->pageSize;

		$criteria = new CDbCriteria();
		if (!empty($params['name'])) {
			$criteria->addSearchCondition('name',$params['name'],true,'AND','LIKE');
		}else{
			$criteria->addCondition('pid<=0');
		}
		$count = self::model()->count($criteria);
		$pages = new CPagination($count);
		$pages->pageSize = $page_size;
		$pages->setCurrentPage($page-1);
		$pages->applyLimit($criteria);
		$result = self::model()->findAll($criteria);

		$list = array();
		if(!empty($result)){
			foreach ($result as $key => $value){
				$list[$key]['area_id'] = $value['area_id'];
				$list[$key]['name'] = $value['name'];
				$list[$key]['pid'] = $value['pid'];
				$list[$key]['fids'] = $value['fids'];
				$list[$key]['first_letter'] = $value['first_letter'];
				$list[$key]['recommend_id'] = $value['recommend_id'];
				$fidvalue = $value['pid']<0 ? 0 : $value['pid'];
				$list[$key]['fid'] = $fidvalue;
				$list[$key]['has_children'] = $this->hasChildren($value['area_id']);
				
				//$list[$key]['tabletree'] = $this->getTreeTable($fidvalue."_".$value['area_id']);
			}
		}
		$listResult['list'] = $list;
		$listResult['pages'] = $pages;

		return $listResult;
	}
	
	/**
	 * 无限极子分类
	 *
	 * @param string $fidstr
	 * @param integer $px
	 * @return string
	 */
	public function getTreeTable($fidstr, $px=20)
	{
		$fidarr = explode('_', $fidstr);
		$pid = array_pop($fidarr);
		$px_num = !empty($fidarr) ? count($fidarr) : 1;
		$px = $px_num * $px;
		$str = '';
		if(!empty($pid)){
			$imagespath = '/static/img/';
			$result = $this->getInfo($pid);
			if(!empty($result)){
				foreach($result as $value){
					$str .= "<tr id=\"".$fidstr."_".$value['area_id']."\">";
                    $str .= "<td><input type='checkbox' class='ids' name='ids[]' value='".$value['area_id']."' /> ".$value['area_id']."</td>";
					$str .= "<td style=\"padding-left:".$px."px;\">";
					if($this->hasChildren($value['area_id'])){
						$str .= "<img class=\"treeicon\" id=\"icon_".$fidstr."_".$value['area_id']."\" border=\"0\" onclick=\"systemTool.getSubTree(this,'".$fidstr."_".$value['area_id']."','/admin/area/getchildren' ,'/static/img/menu_plus.gif' ,'/static/img/menu_minus.gif');\" style=\"margin:3px 0px 0px;\" src=\"$imagespath/menu_plus.gif\" />";
					}
					$str .= "&nbsp;".$value['name'];
					$str .= "</td>";
					$str .= "<td>".$value['first_letter']."&nbsp;</td>";
					$str .= "<td>&nbsp;</td>";
					$str .= "<td>";
					$fidsarr = explode(",", trim($value['fids'],","));
					$str .= count($fidsarr)." 级";
					$str .= "</td>";
					$str .= "<td>";
					if(Yii::app()->user->checkAccess('area,update')){
						$str .= "<a class=\"edit\" href=\"/admin/area/update?id=".$value['area_id']."\">编辑</a>&nbsp;";
					}
					if(Yii::app()->user->checkAccess('area,delete')){
						$str .= "<a class=\"remove\" href=\"javascript:delectSingleMenu('/admin/area/delete?id=".$value['area_id']."');\">删除</a>";
					}
					$str .= "</td>";
					$str .= "</tr>";
					//$str .= $this->getTreeTable($fidstr."_".$value['area_id'], $px);
				}
			}
		}

		return $str;
	}
	
	/**
	 * 根据父级fid获取子一级数据
	 * @param integer $pid
	 * 
	 * @return array
	 */
	public function getInfo($pid)
	{
		$result = self::model()->findAll('pid=:pid',array(':pid'=>$pid));

		return $result;
	}
	
	/**
	 * 根据area_id判断是否存在子级
	 * @param integer $pid
	 * 
	 * @return array
	 */
	public function hasChildren($pid)
	{
		$result = self::model()->count('pid=:pid',array(':pid'=>$pid));
		if($result>0)
		{
			return true;
		}else{
			return false;
		}
	}
	
}